<template>
  <div class="user-manage-container">
    <a-card title="用户管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-form">
        <a-form :model="searchForm" layout="inline" @finish="handleSearch">
          <a-form-item label="用户账号" name="userAccount">
            <a-input
              v-model:value="searchForm.userAccount"
              placeholder="请输入用户账号"
              style="width: 200px"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="用户昵称" name="userName">
            <a-input
              v-model:value="searchForm.userName"
              placeholder="请输入用户昵称"
              style="width: 200px"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="用户角色" name="userRole">
            <a-select
              v-model:value="searchForm.userRole"
              placeholder="请选择用户角色"
              style="width: 120px"
              allow-clear
            >
              <a-select-option value="user">普通用户</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="loading">
                <template #icon><SearchOutlined /></template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮 -->
      <div class="table-actions">
        <a-button type="primary" @click="handleAdd">
          <template #icon><PlusOutlined /></template>
          添加用户
        </a-button>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
        class="user-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userAvatar'">
            <a-avatar :src="record.userAvatar" :size="32">
              {{ record.userName?.charAt(0) || record.userAccount.charAt(0) }}
            </a-avatar>
          </template>
          <template v-else-if="column.key === 'userProfile'">
            <a-tooltip :title="record.userProfile" v-if="record.userProfile">
              <span>{{ truncateText(record.userProfile, 8) }}</span>
            </a-tooltip>
            <span v-else>-</span>
          </template>
          <template v-else-if="column.key === 'userRole'">
            <a-tag :color="record.userRole === 'admin' ? 'red' : 'blue'">
              {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                <template #icon><EditOutlined /></template>
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="handleDelete(record)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button type="link" size="small" danger>
                  <template #icon><DeleteOutlined /></template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑用户弹窗 -->
    <UserEditModal
      v-model:visible="editModalVisible"
      :user-data="currentUser"
      :is-edit="isEdit"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons-vue'
import { userApi } from '@/api/user'
import type { UserVO, UserQueryRequest, DeleteRequest } from '@/types/user'
import { UserEditModal } from '@/components'

// 响应式数据
const loading = ref(false)
const userList = ref<UserVO[]>([])
const editModalVisible = ref(false)
const currentUser = ref<UserVO | null>(null)
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive<UserQueryRequest>({
  userAccount: '',
  userName: '',
  userRole: undefined,
  current: 1,
  pageSize: 10,
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    key: 'userAvatar',
    width: 80,
  },
  {
    title: '用户账号',
    dataIndex: 'userAccount',
    key: 'userAccount',
    width: 140,
  },
  {
    title: '用户昵称',
    dataIndex: 'userName',
    key: 'userName',
    width: 130,
  },
  {
    title: '用户简介',
    dataIndex: 'userProfile',
    key: 'userProfile',
    width: 120,
    ellipsis: true,
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    key: 'userRole',
    width: 100,
  },
  {
    title: '邮箱',
    dataIndex: 'userEmail',
    key: 'userEmail',
    width: 200,
    ellipsis: true,
  },
  {
    title: '手机号',
    dataIndex: 'userPhone',
    key: 'userPhone',
    width: 130,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 160,
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right',
  },
]

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }
    const response = await userApi.listUserVOByPage(params)
    userList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 处理重置
const handleReset = () => {
  searchForm.userAccount = ''
  searchForm.userName = ''
  searchForm.userRole = undefined
  pagination.current = 1
  fetchUserList()
}

// 处理表格变化
const handleTableChange = (pag: { current: number; pageSize: number }) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchUserList()
}

// 处理添加用户
const handleAdd = () => {
  currentUser.value = null
  isEdit.value = false
  editModalVisible.value = true
}

// 处理编辑用户
const handleEdit = (user: UserVO) => {
  currentUser.value = user
  isEdit.value = true
  editModalVisible.value = true
}

// 处理删除用户
const handleDelete = async (user: UserVO) => {
  try {
    const deleteRequest: DeleteRequest = { id: user.id }
    await userApi.deleteUser(deleteRequest)
    message.success('删除用户成功')
    fetchUserList()
  } catch (error) {
    console.error('删除用户失败:', error)
    message.error('删除用户失败')
  }
}

// 处理编辑成功
const handleEditSuccess = () => {
  editModalVisible.value = false
  fetchUserList()
}

// 格式化日期时间 (用于 LocalDateTime)
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  // 处理 LocalDateTime 格式 (YYYY-MM-DDTHH:mm:ss)
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 截断文本
const truncateText = (text: string, maxLength: number) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-manage-container {
  padding: 24px;
}

.search-form {
  margin-bottom: 16px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.table-actions {
  margin-bottom: 16px;
}

.user-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-card-head-title) {
  font-size: 18px;
  font-weight: 600;
}
</style>
